package services

import (
	"errors"
	"gorm.io/gorm"
	"mishop/models"
	"mishop/utils"
)

type ICartService interface {
	FindByID(cartId uint) (*models.Cart, error)
	FindByUserID(page, rows int, userId uint) (*models.Pages, error)
	Create(c *models.Cart) (*models.Cart, error)
	Update(c *models.Cart) (*models.Cart, error)
	Delete(cartId int) error
}
type CartService struct {
	model models.ICart
}
func (p *CartService) FindByID(cartId uint) (*models.Cart, error) {
	return p.model.FindByID(cartId)
}

func (p *CartService) Delete(cartID int) error {
	return p.model.Delete(cartID)
}

func (p *CartService) Update(c *models.Cart) (*models.Cart, error) {
	_, err := p.model.FindByID(c.ID)
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.New("未找到")
	}
	return p.model.Update(c)
}

func (p *CartService) Create(c *models.Cart) (*models.Cart, error) {
	return p.model.Create(c)
}

func (p *CartService) FindByUserID(page, rows int, userId uint) (*models.Pages, error) {
	page, rows = utils.ProcessPagesEntity(page, rows)
	return p.model.FindByUserID(page, rows, userId)
}

func NewCartService(model models.ICart) ICartService {
	return &CartService{model: model}
}
